package com.wzq.upms.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wzq.framework.util.UtilValidate;
import com.wzq.permission.client.model.Pager;
import com.wzq.permission.client.model.admin.DataPermissionModel;
import com.wzq.permission.client.model.admin.MenuModel;
import com.wzq.permission.client.model.admin.RoleDataPerissionModel;
import com.wzq.permission.client.model.admin.RoleMenuModel;
import com.wzq.permission.client.model.admin.RoleModel;
import com.wzq.permission.client.model.admin.UserModel;
import com.wzq.permission.client.service.RoleService;
import com.wzq.upms.core.EasyUiData;
import com.wzq.upms.core.JsonResponse;
import com.wzq.upms.core.SessionUtils;

@RequestMapping("/role")
@Controller
public class RoleController {
	
	@Autowired
	private RoleService roleServiceCient;
	/**
	 * 角色页面
	 */
	private static final String ROLE_VIEW = "role/role";
	
	/**
	 * 用户页面
	 * @param model 模型对象
	 * @param request request对象
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/allList") 
	public ModelAndView  allList(RoleModel model,HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView(ROLE_VIEW);
		return mv;
	}
	
	/**
	 * 用户页面
	 * @param model 模型对象
	 * @param request request对象
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/list") 
	public ModelAndView  list(RoleModel model,HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView(ROLE_VIEW);
		request.setAttribute("applicationId", model.getApplicationId());
		return mv;
	}
	
	/**
	 * 获取数据列表
	 * @param model 模型对象
	 * @param pager 分页对象
	 * @return EasyUiData
	 * @throws Exception
	 */
	@RequestMapping("/dataList") 
	@ResponseBody
	public EasyUiData<RoleModel>  dataList(RoleModel model,Pager pager) throws Exception{
		EasyUiData<RoleModel> data = new EasyUiData<RoleModel>();
		List<RoleModel> roleLst = roleServiceCient.queryList(model, pager);
		data.setTotal(roleServiceCient.queryByCount(model));
		data.setRows(roleLst==null?new ArrayList():roleLst);
		return data;
	}
	
	
	/**
	 * 添加或修改数据
	 * @param model 模型对象
	 * @throws Exception
	 */
	@RequestMapping("/add")
	@ResponseBody
	public JsonResponse add(RoleModel model,HttpServletRequest request) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"保存成功");
		RoleModel tempRole = new RoleModel();
		tempRole.setApplicationId(model.getApplicationId());
		tempRole.setRoleName(model.getRoleName());
		if(StringUtils.isNotEmpty(model.getRoleKey())){
		    tempRole.setRoleKey(model.getRoleKey());
		}
		if(roleServiceCient.isExist(tempRole)>0){
		    response.setMsg("该角色名或key已存在,请重新输入");
            response.setResult(JsonResponse.FAIL);
		}else{
		    UserModel role = SessionUtils.getUser(request);
	        model.setCreateUser(role.getUserName());
	        model.setUpdateUser(role.getUserName());
	        roleServiceCient.add(model);
		}
		return response;
	}
	
	/**
	 * 添加或修改数据
	 * @param model 模型对象
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public JsonResponse edit(RoleModel model,HttpServletRequest request) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"修改成功");
		RoleModel tempRole = new RoleModel();
        tempRole.setApplicationId(model.getApplicationId());
        tempRole.setRoleName(model.getRoleName());
        if(StringUtils.isNotEmpty(model.getRoleKey())){
            tempRole.setRoleKey(model.getRoleKey());
        }
        tempRole.setRoleId(model.getRoleId());
        if(roleServiceCient.isExist(tempRole)>0){
            response.setMsg("该角色名或key已存在,请重新输入");
            response.setResult(JsonResponse.FAIL);
        }else{
    		UserModel role = SessionUtils.getUser(request);
    		model.setUpdateTime(new Date());
    		model.setUpdateUser(role.getUserName());
    		roleServiceCient.updateBySelective(model);
        }
		return response;
	}
	
	/**
	 * 根据ID查找对象
	 * @param roleId  
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/getById")
	@ResponseBody
	public RoleModel getById(Long roleId) throws Exception{
		RoleModel model = roleServiceCient.queryById(roleId);
		return model;
	}
	
	/**
	 * 删除数据
	 * @param roleIds 主键列表
	 * @param response 
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public JsonResponse delete(Long[] roleIds) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"删除成功");
		roleServiceCient.logicDelete(roleIds);
		return response;
	}
	
	/**
	 * 角色授权保存
	 * @param roleIds 主键列表
	 * @param response 
	 * @throws Exception
	 */
	@RequestMapping("/distribution")
	@ResponseBody
	public JsonResponse distributionSave(String menuId,Long roleId,HttpServletRequest request) throws Exception{
		
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"授权成功");
		String[] menuIds={};
		if(UtilValidate.isNotEmpty(menuId)){//截取菜单的id
			menuIds=menuId.split(",");
		}
		
		List<RoleMenuModel> roleMenuList=new ArrayList<RoleMenuModel>();
		UserModel role = SessionUtils.getUser(request);
		
		for (int i = 0; i < menuIds.length; i++) {//添加菜单记录
			RoleMenuModel roleMenu=new RoleMenuModel();
			roleMenu.setMenuId(Long.valueOf(menuIds[i]));
			roleMenu.setRoleId(roleId);
			roleMenu.setCreateTime(new Date());
			roleMenu.setUpdateTime(new Date());
			roleMenu.setCreateUser(role.getUserName());
			roleMenu.setUpdateUser(role.getUserName());
			roleMenuList.add(roleMenu);
		}
		roleServiceCient.distributionSave(roleMenuList, roleId);
	
		return response;
	}
	
	/**
	 * 获取角色id的菜单
	 * @param roleIds 主键列表
	 * @param response 
	 * @throws Exception
	 */
	@RequestMapping("/getdistributionRoleMenu")
	@ResponseBody
	public List<MenuModel> getdistributionRoleMenu(Long roleId) throws Exception{
	
		List<MenuModel> result = roleServiceCient.queryPermissionsByRoleId(roleId);
		return result;
	}
	

	/**
	 * 获取角色id的数据权限
	 * @param roleId 主键列表
	 * @throws Exception
	 */
	@RequestMapping("/getDataById")
	@ResponseBody
	public List<Long> getDataById(Long roleId) throws Exception{
	List<Long> list=roleServiceCient.getRoleDataPerissionByRoleId(roleId);
	return list;
	
	}
	
	
	/**
	 * 获取系统数据权限
	 * @param model 模型对象
	 * @param pager 分页对象
	 * @return EasyUiData
	 * @throws Exception
	 */
	@RequestMapping("/getpremissionDataList") 
	@ResponseBody
	public List<DataPermissionModel>  getpermissionDataList(Long applicationId,Integer rangeType) throws Exception{
		/*EasyUiData<DataPerissionModel> data = new EasyUiData<DataPerissionModel>();*/
		List<DataPermissionModel> dataPerissionLst = roleServiceCient.queryApplicationDataList(applicationId,rangeType);
		return dataPerissionLst;
	}
	
	
	/**
	 * 分配数据权限保存
	 * @param dataPermissionIds 数据权限id集合
	 * @param roleIds 角色ID
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/distributionDataSave")
	@ResponseBody
	public JsonResponse distributionDataPerissionSave(Long roleId,Long[] dataPermissionIds,HttpServletRequest request)throws Exception{
		
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"分配数据权限成功");
		
		if(dataPermissionIds!=null && dataPermissionIds.length>0){
			UserModel user = SessionUtils.getUser(request);
			List<RoleDataPerissionModel> roleDataPerissionModelList = new ArrayList<RoleDataPerissionModel>();
			for(Long dataPermissionId:dataPermissionIds){
				RoleDataPerissionModel dataPerissionModel = new RoleDataPerissionModel();
				dataPerissionModel.setRoleId(roleId);
				dataPerissionModel.setDataPerissionId(dataPermissionId);
				dataPerissionModel.setCreateUser(user.getUserName());
				dataPerissionModel.setUpdateUser(user.getUserName());
				roleDataPerissionModelList.add(dataPerissionModel);
			}
			
			roleServiceCient.saveDataPerssion(roleDataPerissionModelList, roleId);
		}
		
		return response;
	} 
	
	
	
}
